<template>
  <ex-dialog
    width="900px"
    class="ex-diolog"
    :title="title"
    :visible="visible"
    @closeDialog="handleClose"
  >	
		<el-form :model="ruleForm" status-icon :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
      <el-form-item label="快讯标题" prop="title">
				<el-input type="text" v-model="ruleForm.title" autocomplete="off" placeholder="请输入快讯标题"></el-input>
			</el-form-item>
      <el-form-item label="快讯正文：" prop="text">
        <div class="richText">
          <Toolbar style="border-bottom: 1px solid #ccc" :editor="editor" :defaultConfig="toolbarConfig"
            :mode="mode" />
          <Editor style="height: 500px; overflow-y: hidden;" v-model="ruleForm.text" :defaultConfig="editorConfig"
            :mode="mode" @onCreated="onCreated"  @onChange="onChange"/>
        </div>
      </el-form-item>
      <el-form-item label="来源" prop="source">
				<el-input type="text" v-model="ruleForm.source" autocomplete="off" placeholder="请输入来源"></el-input>
			</el-form-item>
      <el-form-item label="更新时间" prop="updateTime">
				<el-date-picker v-model="ruleForm.updateTime" placeholder="请输入更新时间" type="datetime" format="yyyy-MM-dd HH:mm" value-format="yyyy-MM-dd HH:mm" >
        </el-date-picker>
			</el-form-item>
      <el-form-item label="快讯状态:" prop="status">
				<el-switch
          v-model="ruleForm.status"
          active-text="显示"
          inactive-text="隐藏"
          active-value="1"
          inactive-value="2">
        </el-switch>
			</el-form-item>
			<el-form-item>
				<el-button type="primary" @click="submitForm('ruleForm')" :loading="loading">确认</el-button>
				<el-button @click="handleClose('ruleForm')">取消</el-button>
			</el-form-item>
		</el-form>
  </ex-dialog>
</template>
<script>
// components
import Loading from '@/components/Loading/index'
// api
import {
  addNews,
  editNews,
  newDetail
} from '@/api/kyyOfficialWebsite/newsManagement'
import '@wangeditor/editor/dist/css/style.css'
import {
  Editor,
  Toolbar
} from "@wangeditor/editor-for-vue";
export default {
  components: {
    Loading,
    Editor,
    Toolbar
  },
  props: {
    visible: Boolean,
    id: String,
    pathType: String,
  },
  data() {
    var validateMinBetAmount= (rule, value, callback) => {
      var reg = /(^[1-9]\d*$)/
      if (value === '') {
        callback(new Error('填写最低下注金额'));
      } else if (!reg.test(value)) {
        callback(new Error('请填写大于0的整数'));
      }  else {
        callback();
      }
    };
    return {
      loading: false,
      title: '新增快讯',
      betTypeList: [
        {id: '1',value: '神椰coco'}
      ],
      typeList: [
        {id: '1',value: '支持竞猜'},
        {id: '2',value: '冠军竞猜'},
      ],
      roleList: [],
			ruleForm: {
        id: '',//		id
				source: '',//来源
				status: '1',//快讯状态（1显示 2隐藏）
        text: '',//	正文
        title: null,//标题
        updateTime: '',
      },
      flags: false,
			rules: {
        source:   [
          { required: true,message: '请填写来源',trigger: 'blur' }
        ],
        status: [
          { required: true,message: '请选择',trigger: 'change' }
        ],
        text: [
          { required: true,message: '请填写正文',trigger: 'blur' }
        ],
        title: [
          { required: true,message: '请填写标题', trigger: 'blur' }
        ],
        updateTime: [
          { required: true,message: '请选择时间',trigger: 'change' }
        ],
      },
      // 富文本配置
      logoUploadUrlImg: process.env.VUE_APP_BASE_API + "/common/v1/uploadFile", //图片接口
      videoUploadUrl: process.env.VUE_APP_BASE_API + "/common/v1/uploadFile", //视频接口
      editor: null,
      html: "<p>hello&nbsp;world</p>",
      toolbarConfig: {
        // toolbarKeys: [ /* 显示哪些菜单，如何排序、分组 */ ],
        // excludeKeys: [ /* 隐藏哪些菜单 */ ],
        excludeKeys:['group-video']
      },
      editorConfig: {

        placeholder: "请输入内容...",
        // autoFocus: false,
        // 所有的菜单配置，都要在 MENU_CONF 属性下
        MENU_CONF: {},
      },
      mode: 'default', // or 'simple'
    }
  },
  computed: {
   
  },
  created() {
    var _this = this
    // 配置上传图片
    var name = ''
    this.editorConfig.MENU_CONF['uploadImage'] = {
      server: _this.logoUploadUrlImg,
      // headers: _this.headers,
      fieldName: 'file',
      //    async customUpload(file, insertFn) {
      //        console.log(file)
      //     // file 即选中的文件
      //     // 自己实现上传，并得到图片 url alt href
      //     // 最后插入图片
      //     //   insertFn(url, alt, href)
      //     },
      onSuccess(file, res) {
        name = file.name
        // console.log(`${file.name} 上传成功`, res)
      },
      customInsert(res, insertFn) {
        console.log(res)
        insertFn(res.result.url, name, res.result.url)
      }
    }
    // 配置上传视频
    this.editorConfig.MENU_CONF['uploadVideo'] = {
      server: _this.videoUploadUrl,
      // headers: _this.headers,
      fieldName: 'file',
      maxFileSize: 500 * 1024 * 1024,
      //    async customUpload(file, insertFn) {
      //        console.log(file)
      //     // file 即选中的文件
      //     // 自己实现上传，并得到图片 url alt href
      //     // 最后插入图片
      //     //   insertFn(url, alt, href)
      //     },
      customInsert(res, insertFn) {
        // res 即服务端的返回结果
        // 从 res 中找到 url ，然后插入
        insertFn(res.result.url)
      },
    }
    if(this.pathType == 'edit'){
      this.title = '编辑快讯'
      setTimeout(() => {
        this.getDetail()
      }, 100)
    } else if(this.pathType == 'add'){
      this.ruleForm.id = ''
    }   

	},
  methods: {
    onCreated(editor) {
      this.editor = Object.seal(editor); // 【注意】一定要用 Object.seal() 否则会报错
      console.log('this.editor',this.editor)
    },
    onChange(editor) {
      console.log("onChange", editor.getHtml()); // onChange 时获取编辑器最新内容
    },
    getEditorText() {
      const editor = this.editor;
      if (editor == null) return;

      console.log(editor.getText()); // 执行 editor API
    },
    printEditorHtml() {
      const editor = this.editor;
      if (editor == null) return;

      console.log(editor.getHtml()); // 执行 editor API
    },
    //活动详情
    getDetail(){
      var id = this.id
      console.log('id',id)
      newDetail(id).then(res => {
        this.ruleForm = res.result
        this.ruleForm.text = res.result.text
      })
    },
    //新建子账号
    submitForm(formName) {
      console.log('formName',formName)
      this.$refs[formName].validate((valid) => {
        console.log('valid',valid)
        if (valid) {
          this.loading = true
          if(this.pathType == 'add'){
            var data = {
              ...this.ruleForm
            }
            console.log('data',data)
            addNews(data).then(res => {
              this.handleSuccess("创建成功")
              setTimeout(() => {
                this.loading = false
              }, 1000);
            }).catch(()=>{
               this.loading = false
            }).finally(() => {

            })
          }else if(this.pathType == 'edit'){
            var data = {
              ...this.ruleForm
            }
            editNews(data).then(res => {
              this.handleSuccess("修改成功")
              setTimeout(() => {
                this.loading = false
              }, 1000);
            }).catch(()=>{
               this.loading = false
            }).finally(() => {
            })
          }
           
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    
		//取消
    handleClose(formName) {
      this.$emit('update:visible', false)
			// this.$refs[formName].resetFields();
    },
		//确认
		handleConfirm(){
			this.$emit('success', '你好')
		},
    handleSuccess(msg) {
      if (msg === '已拒绝') {
        var type = 'error'
      } else {
        var type = 'success'
      }
      this.$message({
        message: msg,
        type: type,
        duration: 1000,
        onClose: () => {
          this.handleClose()
          this.$emit('success')
        }
      })
    },
  }
}
</script>
<style lang="scss" scoped>
.ex-diolog {
  ::v-deep .ex--dialog--footer {
    border: none !important;
		padding: 0 !important;
  }
	::v-deep .ex--dialog--main {
    padding: 10px 20px !important; 
  }
}
::v-deep .avatar-uploader2 .el-upload {
  width: 100% !important;
}

.avatar-uploader2 {
  width: 130px;
  height: 130px;
  text-align: center;
  line-height: 130px;
  background-color: #fbfdff;
  border: 1px dashed #c0ccda;
}

.banner_img {
  width: 130px;
  height: 130px;
}

.richText {
  border: 1px solid #ccc;
  line-height: normal;
}
</style>